<template>
  <div class="login-box" :class="admin">
    <div class="login-info-box">
      <h1 class="page-title">{{$t("Survey")}}</h1>
      <a-form layout="horizontal" :model="formState" @finish="loginInSystem">
        <a-form-item :label="$t('Username')">
          <a-input v-model:value="formState.user" :placeholder="$t('Username')">
            <template #prefix>
              <UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item :label="$t('Password')">
          <a-input v-model:value="formState.password" type="Password" :placeholder="$t('Password')">
            <template #prefix>
              <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" style="width: 100%" :disabled="formState.user === '' || formState.password === ''">
           {{$t('Login In')}} 
          </a-button>
        </a-form-item>
      </a-form>
    </div>
    
</div>

</template>
<script lang="ts" setup>
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import {  reactive, UnwrapRef, ref } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter, useRoute } from 'vue-router'
import { setCookie, getCookie } from "../utils/common"

import { handleLogin } from "../api/survey"

interface FormState {
  user: string;
  password: string;
}
const formState: UnwrapRef<FormState> = reactive({
    user: "",
    password: "",
});
const router = useRouter()

const loginInSystem = ()=> {

  let data = {
    "userName": formState.user,
    "password": formState.password,
  }
  
  
  handleLogin(data).then(res => {
    
    if(res?.status == 200 && !res?.data?.flag){
      message.error(res.data.msg);
      return
    }

    if (res?.status == 200 && res?.data?.data?.token) {
      let userType = res?.data?.data?.userType;
      let token = res?.data?.data?.token;
      setCookie('survey_user_token', token, 0.125)
      window.localStorage.setItem("user_info", JSON.stringify(res?.data?.data))
      window.localStorage.setItem("user_type", userType)
      if (userType === 'admin') {
        router.push({path: '/surveyPublish'})
      } else {
        router.push({path: '/surveyList'})
      }
    }
  })
}
</script>